-- Leviathan (c) v.v.balashoff
local ButtonAsyncPressedComponent = require('leviathan/ECS/Input/Components/ButtonAsyncPressedComponent')
local ButtonHoldComponent = require('leviathan/ECS/Input/Components/ButtonHoldComponent')
local ButtonPressedComponent = require('leviathan/ECS/Input/Components/ButtonPressedComponent')
local Class = require('leviathan/Class')

local MouseClickSystem = Class:derive('InputMouseClickSystem')

function MouseClickSystem:new(domain)
    self.name = 'InputMouseClickSystem'
    self.domain = domain
end

function MouseClickSystem:update(dt)
    local domain = self.domain
    local input = domain.components['Input']
    -- clear all async components
    if input then
        for _, c in pairs(input) do
            if c.id == 'ButtonAsyncPressedComponent' then
            end
        end
    end
end

-- mouse handler functions

function love.mousepressed(x, y, button, istouch)
    local inp = world:getDomain('Input')
    local e
    if button == 1 then
        e = inp:getEntity('MouseLeftButton')
print('MB 1 pressed')
    end
    if button == 2 then
        e = inp:getEntity('MouseRightButton')
print('MB 2 pressed')
    end
    if button == 3 then
        e = inp:getEntity('MouseMiddleButton')
print('MB 3 pressed')
    end
    if e then
--        local h = e.components['ButtonHoldComponent']
--        if h then
--        print('HHHH!')
--        end
--print('INPUT MOUSE PRESSED')
--e:dump()
--print('____')
        if e.components['ButtonHoldComponent'] then
        print('Y')
        else
        print('N')
        end
        e:addComponent(ButtonAsyncPressedComponent())
        e:addComponent(ButtonHoldComponent())
    else
        print('ERROR! NO BUTTON!')
    end
--e:dump()
--print('____ENDED____')
end

function love.mousereleased(x, y, button)
print('HERE: MouseClickSystem.lua; function love.mousereleased')
    local inp = world:getDomain('Input')
    local e
    if button == 1 then
        e = inp:getEntity('MouseLeftButton')
print('  MB 1 released')
    end
    if button == 2 then
        e = inp:getEntity('MouseRightButton')
print('  MB 2 released')
    end
    if button == 3 then
        e = inp:getEntity('MouseMiddleButton')
print('  MB 3 released')
    end
    if e then
        -- remove ButtonAsyncPressedComponent
        local compPress = e:getComponent('ButtonAsyncPressedComponent')
        if compPress then
            e:deleteComponent(compPress)
        end
        -- remove ButtonHoldComponent
        local compHold = e:getComponent('ButtonHoldComponent')
        if compHold then
print('  Button held for:', compHold.time)
            e:deleteComponent(compHold)
        end
    else
        print('ERROR! NO BUTTON!')
    end
end

return MouseClickSystem
